<?php

namespace app\api\controller;

use addons\thirdwork\library\Application;
use app\common\controller\Api;
use EasyWeChat\Factory;

/**
 * 首页接口
 */
class Index extends Api
{
	protected $noNeedLogin = ['*'];
	protected $noNeedRight = ['*'];

	/**
	 * 首页
	 *
	 */
	public function index()
	{
		$this->success('请求成功');
	}

	public function notice()
	{
		$thirdwork = get_addon_config('thirdwork');
		$config    = [
			'corp_id'  => $thirdwork['wechatwork']['corpid'] ?? '',
			'agent_id' => $thirdwork['wechatwork']['agentid'] ?? '',
			'secret'   => $thirdwork['wechatwork']['corpsecret'] ?? '',
			'token'    => $thirdwork['wechatwork']['messagetoken'] ?? '',
			'aes_key'  => $thirdwork['wechatwork']['messageaeskey'] ?? ''
		];
		$app       = Factory::work($config);
		$app->server->push(function ($message) use ($app) {
			notify_log($message);
			if (isset($message['Event']) && isset($message['EventKey']) && $message['Event'] == 'template_card_event') {
				list($eventKey, $user_id) = explode('_', $message['EventKey']);
				if ($eventKey == 'yes') {
					$app->message->updateTemplateCard([$message['FromUserName']], $message['AgentID'], $message['ResponseCode'], '已同意');
					$user = \app\common\model\User::where(['id' => $user_id])->find();
					if ($user) {
						$user->querypwd = NULL;
						$user->save();
						$work = new Application(get_addon_config('thirdwork'));
						$work->wechatwork->sendTextMessage('您的识别码已重置，请访问应用设置新的识别码。', $user['username']);
					}
				} else {
					$app->message->updateTemplateCard([$message['FromUserName']], $message['AgentID'], $message['ResponseCode'], '已拒绝');
				}
			}
			return '';
		});
		$response = $app->server->serve();
		$response->send();
	}

}
